var bar, foo, zer;
var langs = require("./langs.js")
const axios = require('axios');

async function getDicts() {
	const url = 'static/data.json';
	const url0 = 'static/dicts.json';
	const url1 = 'static/homo.json';
	try {
		const res = await axios.get(url);
		bar = res.data
		const res1 = await axios.get(url0);
		foo = res1.data
		const res2 = await axios.get(url1);
		zer = res2.data
	} catch (error) {
		console.error(error);
	}
	return zer
}

module.exports = {
	data() {
		return {
			langs: langs,
			uni: {},
			isStory: false,
			linkId: "",
			homeId: "",
			subs: [],
			linkWords: [],
			homoWords: [],
			Id: "",
			subId: "",
			lang: "en",
		}
	},
	onLoad: function(e) {
		getDicts().then(() => {
			if (e.title) {
				var v = this.getByTitle(e.title);
				console.log(v);
				if (v) this.mixdata(v)
			}
			if (e.id) {
				var dict = this.getByDictId(e.id, e.lang)
				if (dict) this.mixdata(dict)
				this.mixdata(this.getById(e.id))
			}
			console.log('getDicts', this.$data);
			this.onLoaddata()
		})
	},
	onShow: function() {
		return
		setTimeout(() => {
			uni.setNavigationBarTitle({
				title: navTitle
			})
		})
	},
	methods: {
		onLoaddata: function() {
			console.log('load data 1');
		},
		goDict(event, para) {
			// console.log("dict...",event);
			uni.navigateTo({
				url: 'dict?id=' + para.id + '&lang=' + para.lang
			});
		},
		goNext(event, para) {
			// console.log("subs...",event,para);
			uni.navigateTo({
				url: 'step1?lang=' + this.lang + '&title=' + para.title
			});
		},
		getByTitle: function(title) {
			var obj = bar.find((v) => v.title == title);
			if (obj && obj.subId) {
				obj.subs = [];
				obj.subId.forEach((v) => obj.subs.push(this.getById(v)))
			}
			if (obj && obj.linkId) {
				obj.uni = bar.find((v) => v._id == obj.linkId)
				if (obj.uni.isMore) {
					obj.uni.linkMore = bar.filter((v) => (v.linkId == obj.uni._id && v.lang != undefined))
				}
				obj.linkWords = bar.filter((v) => v.subId && v.subId[0] == obj._id)
			}
			if (obj && obj.homeId) {
				obj.homoWords = bar.filter((v) => v.title != obj.title && zer.words.indexOf(v._id) >= 0)
			}
			if (obj) obj.Id = obj._id
			return obj;
		},
		getById: function(id) {
			return bar.find((v) => v._id == id)
		},
		getByDictId: function(id, lang) {
			return foo.find((v) => (v.id == id && v.lang == lang))
		},
		mixdata: function(v) {
			if (!v) return;
			for (var key in v) {
				if (v.hasOwnProperty(key)) {
					var element = v[key];
					this.$data[key] = element;
				}
			}

		},
		getLangById: function(id) {
			return langs.find((v) => v.value == id).text
		},
		getLangText: function(la) {
			switch (la) {
				case "fr":
					return this.getLangById(2)
					break;
				case "ru":
					return this.getLangById(7)
					break;
				case "es":
					return this.getLangById(4)
					break;
				default:
					return this.getLangById(1)
					break;
			}
		}
	}
}